package com.aoxon.cargo.database;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build.VERSION;
import android.util.Log;

import com.aoxon.cargo.bean.Cloth;
import com.aoxon.cargo.bean.Supplier;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.DataUtil;

public class DataService {
	private final DatabaseHelper dbHelper;
	private String tag = "DataService";
	public DataService(Context context) {
		// TODO Auto-generated constructor stub
		dbHelper = new DatabaseHelper(context, "cargo.db", null, 3);
	}

	// private static SQLiteDatabase db;

	// startClothId为起始的ClothId,将不返回clothId所指之前(包括自身)的Cloth,一开始不知道可以填0
	public List<Cloth> getClothes(int startId, int length, int type) {
		List<Cloth> list = new ArrayList<Cloth>();
		String sql = "select * from cloth where(type = ?)";
		Cursor cursor = dbHelper.getReadableDatabase().rawQuery(sql,
				new String[] { String.valueOf(type) });
		if (startId > 0) {
			while (startId > 0 && cursor.moveToNext()) {
				startId--;
			}

		}
		while (cursor.moveToNext() && length > 0) {
			list.add(DataUtil.gson.fromJson(cursor.getString(2), Cloth.class));
			length--;
		}
		if (VERSION.SDK_INT < 14) {
			cursor.close();
		}
		Log.v(tag + "_getClothes", DataUtil.gson.toJson(list));
		return list;
	}

//	public List<Cloth> getClothes(String userId, int startId, int length, int type) {
//
//		List<Cloth> list = new ArrayList<Cloth>();
//
//		try {
//			List<String> toIds = getToId(userId, startId, length, type);
//			for (int i = 0; i < toIds.size(); i++) {
//				list.add(getCloth(Integer.parseInt(toIds.get(i))));
//			}
//			Log.v(tag + "getCloth", DataUtil.gson.toJson(list));
//			return list;
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return null;
//	}

	public List<Cloth> getClothes(String userId, int startId, int length, int type) {

		List<Cloth> list = new ArrayList<Cloth>();

		try {
			List<String> toIds = getToId(userId, startId, length, type);
			for (int i = 0; i < toIds.size(); i++) {
				list.add(getCloth(Integer.parseInt(toIds.get(i))));
			}
			Log.v(tag + "_getClothes" + "getCloth", DataUtil.gson.toJson(list));
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public List<Supplier> getSuppliers(String userId, int startId, int length,
			int type) {
		try {
			List<Supplier> list = new ArrayList<Supplier>();
			if (type != MyStateUtil.PHONE_RECORD) {
				List<String> toIds = getToId(userId, startId, length, type);

				for (int i = 0; i < toIds.size(); i++) {
					list.add(getSupplier(Integer.parseInt(toIds.get(i))));
				}
			} else {
				List<Map<String, String>> toIds = new ArrayList<Map<String, String>>();
				toIds = getToId(userId, startId, length, type, true);
				for (int i = 0; i < toIds.size(); i++) {
					Supplier sup = getSupplier(Integer.parseInt(toIds.get(i)
							.get("toId")));
					String str = toIds.get(i).get("time");
					sup.setSaveTime(str.substring(0, str.length() - 3));
					list.add(sup);
				}
			}
			Log.v(tag + "_getClothes" + "getSuppliers", DataUtil.gson.toJson(list));
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// startId 为 已获得的数量
	// 获取数据不包含startId
	public List<String> getToId(String userId, int startId, int length, int type) {

		String sql = "select toId from stat ";
		try {
			List<String> list = new ArrayList<String>();
			Cursor cursor;
			// if (userId != 0) {
			switch (type) {
			case MyStateUtil.COMMOM:
				sql += " where(fromId = ?)";
				cursor = dbHelper.getReadableDatabase().rawQuery(sql,
						new String[] { String.valueOf(userId) });
				break;
			default:// 收藏
				sql += " where(fromId=? and type = ?)";
				cursor = dbHelper.getReadableDatabase().rawQuery(
						sql,
						new String[] { String.valueOf(userId),
								String.valueOf(type) });
				break;
			}
			// } else {
			// sql += " where(type = ?)";
			// cursor = dbHelper.getReadableDatabase().rawQuery(sql,
			// new String[] { String.valueOf(type) });
			// }

			if (length <= 0) {
				while (cursor.moveToNext()) {
					list.add(cursor.getString(0));
				}
				return list;
			}
			// 找到起始Id的cursor
			while (startId > 0 && cursor.moveToNext()) {
				startId--;
			}
			// 继续添加length个
			while (cursor.moveToNext() && length != 0) {
				list.add(cursor.getString(0));
				length--;
			}
			if (VERSION.SDK_INT < 14) {
				cursor.close();
			}
			return list;
		} catch (Exception e) {

			e.printStackTrace();
		}
		return null;
	}

	public List<Map<String, String>> getToId(String userId, int startId,
			int length, int type, boolean isMap) {

		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		String sql = "select toId ,time from stat ";
		try {
			Cursor cursor;
			if (userId != null) {
				switch (type) {
				case MyStateUtil.COMMOM:
					sql += " where(fromId = ?)";
					cursor = dbHelper.getReadableDatabase().rawQuery(sql,
							new String[] { String.valueOf(userId) });
					break;
				default:// 收藏
					sql += " where(fromId=? and type = ?)";
					cursor = dbHelper.getReadableDatabase().rawQuery(
							sql,
							new String[] { String.valueOf(userId),
									String.valueOf(type) });
					break;
				}
			} else {
				sql += " where(type = ?)";
				cursor = dbHelper.getReadableDatabase().rawQuery(sql,
						new String[] { String.valueOf(type) });
			}

			if (length <= 0) {// 获取所有
				while (cursor.moveToNext()) {
					Map<String, String> map = new HashMap<String, String>();
					map.put("toId", cursor.getString(0));
					map.put("time", cursor.getString(1));
					list.add(map);
				}
				return list;
			}
			// 找到起始Id的cursor
			while (startId > 0 && cursor.moveToNext()) {
				// if (cursor.getInt(0) == startId) {
				// // length--;
				// break;
				// }
				startId--;
			}
			// 继续添加length个
			while (cursor.moveToNext() && length != 0) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("toId", cursor.getString(0));
				map.put("time", cursor.getString(1));
				list.add(map);
				length--;
			}
			if (VERSION.SDK_INT < 14) {
				cursor.close();
			}
			return list;
		} catch (Exception e) {

			return list;
		}
	}

	public Cloth getCloth(int clothId) {
		String sql = "select * from cloth where(clothId = ?)";
		Cursor cursor = null;
		try {
			cursor = dbHelper.getReadableDatabase().rawQuery(sql,
					new String[] { String.valueOf(clothId) });
			if (cursor.moveToNext()) {
				return DataUtil.gson.fromJson(cursor.getString(2), Cloth.class);

			} else {

				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (VERSION.SDK_INT < 14) {
				if (cursor != null) {
					cursor.close();
				}
			}
		}

	}

	public Supplier getSupplier(int supId) {
		String sql = "select * from supplier where(supId = ?)";
		Cursor cursor =null ;
		try {
			cursor = dbHelper.getReadableDatabase().rawQuery(sql,
				new String[] { String.valueOf(supId) });
			if (cursor.moveToNext()) {
				return DataUtil.gson.fromJson(cursor.getString(2),
						Supplier.class);
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if(cursor!=null){
				if (VERSION.SDK_INT < 14) {
					cursor.close();
				}
			}
			
		}
	}

	public boolean insertCloth(Cloth cloth, int type) {
		String sql = "insert or ignore into  cloth (clothId,type,strJson)values(?,?,?)";
		try {
			dbHelper.getWritableDatabase()
					.execSQL(
							sql,
							new String[] { String.valueOf(cloth.getClothId()),
									String.valueOf(type),
									DataUtil.gson.toJson(cloth) });
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean insertSupplier(Supplier sup, int type) {
		String sql = "insert or ignore into  supplier (supId,type,strJson)values(?,?,?)";
		try {
			dbHelper.getWritableDatabase().execSQL(
					sql,
					new String[] { String.valueOf(sup.getSupId()),
							String.valueOf(type), DataUtil.gson.toJson(sup) });
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean insertStat(String fromId, int toId, int type, String time) {
		String sql = "insert into stat (fromId,toId,type,time)values(?,?,?,?)";
		try {
			dbHelper.getWritableDatabase().execSQL(
					sql,
					new String[] { String.valueOf(fromId),
							String.valueOf(toId), String.valueOf(type), time });
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean insertStat(String fromId, String toId, int type, String time) {
		String sql = "insert into stat (fromId,toId,type,time)values(?,?,?,?)";
		try {
			dbHelper.getWritableDatabase().execSQL(
					sql,
					new String[] { fromId,
							toId, String.valueOf(type), time });
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean deleteCollection(String fromId, int toId, int type) {
		String sql = "delete from stat ";
		try {
			if (fromId == null) {
				sql += " where (toId = ? and type = ?)";
				dbHelper.getWritableDatabase().execSQL(
						sql,
						new String[] { String.valueOf(toId),
								String.valueOf(type) });

			} else {
				sql += " where (fromId = ? and toId = ? and type =?)";
				dbHelper.getWritableDatabase().execSQL(
						sql,
						new String[] { String.valueOf(fromId),
								String.valueOf(toId), String.valueOf(type) });
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

}
